package com.goldsprite.projecttemplategenerator.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import androidx.core.content.FileProvider;

import java.io.File;

public class ApkInstaller {

	public static final int REQUEST_CODE_INSTALL_PERMISSION = 1001;

	/**
	 * 检查是否有安装未知来源应用的权限
	 */
	public static boolean hasInstallPermission(Context context) {
		return Build.VERSION.SDK_INT < Build.VERSION_CODES.O || context.getPackageManager().canRequestPackageInstalls();
	}

	/**
	 * 请求安装未知来源应用的权限
	 */
	public static void requestInstallPermission(Activity activity) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
			intent.setData(Uri.parse("package:" + activity.getPackageName()));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			activity.startActivityForResult(intent, REQUEST_CODE_INSTALL_PERMISSION);
		}
	}

	/**
	 * 安装 APK
	 */
	public static void installApk(Activity activity, File apkFile) {
		Uri apkUri;
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			apkUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", apkFile);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		} else {
			apkUri = Uri.fromFile(apkFile);
		}

		intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
		activity.startActivity(intent);
	}
}
